import 'dart:async';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_nft/api/API.dart';
import 'package:flutter_nft/provider/LoginProvider.dart';
import 'package:provider/provider.dart';
class ProductList {
  late int id;
  late String productCode;
  late String productTitle;
  late String productImage;
  late String productDesc;
  late int initPrice;
  late int newPrice;
  late int productCount;
  late int productStock;
  late int orgAuthId;
  late String createTime;
  late String updateTime;
  late String productTime;
  late int dFlag;
  late String orgName;
  late String orgLogo;

  static ProductList? fromMap(Map<String, dynamic> map) {
    if (map == null) return null;
    ProductList productListBean = ProductList();
    productListBean.id = map['id'];
    productListBean.productCode = map['productCode'];
    productListBean.productTitle = map['productTitle'];
    productListBean.productImage = map['productImage'];
    productListBean.productDesc = map['productDesc'];
    productListBean.initPrice = map['initPrice'];
    productListBean.newPrice = map['newPrice'];
    productListBean.productCount = map['productCount'];
    productListBean.productStock = map['productStock'];
    productListBean.orgAuthId = map['orgAuthId'];
    productListBean.createTime = map['createTime'];
    productListBean.updateTime = map['updateTime'];
    productListBean.productTime = map['productTime'];
    productListBean.dFlag = map['dFlag'];
    productListBean.orgName = map['orgName'];
    productListBean.orgLogo = map['orgLogo'];
    return productListBean;
  }

  Map toJson() => {
    "id": id,
    "productCode": productCode,
    "productTitle": productTitle,
    "productImage": productImage,
    "productDesc": productDesc,
    "initPrice": initPrice,
    "newPrice": newPrice,
    "productCount": productCount,
    "productStock": productStock,
    "orgAuthId": orgAuthId,
    "createTime": createTime,
    "updateTime": updateTime,
    "productTime": productTime,
    "dFlag": dFlag,
    "orgName": orgName,
    "orgLogo": orgLogo,
  };
}

class DigitalCollection extends StatefulWidget {
  @override
  _DigitalCollectionState createState() => _DigitalCollectionState();
}

class _DigitalCollectionState extends State<DigitalCollection> {
  //List<Map> dataList = [];

  List<ProductList?> mapLists = [];

  int leftSeconds = 3700;

  late Timer? _timer;

  int newTime(){
    return int.parse(new DateTime.now().millisecondsSinceEpoch.toString());
  }

  //根据总秒数转换为对应的 hh:mm:ss 格式
  static String constructTime(int secondss) {
    int seconds = (secondss / 1000).ceil();
    if(seconds > 0){
      int day = seconds ~/ 3600 ~/ 24;
      int hour = seconds ~/ 3600 % 24;
      int minute = seconds % 3600 ~/ 60;
      int second = seconds % 60;
      // if(day != 0){
      //   return formatTime(day)+'天'+formatTime(hour) + "小时" + formatTime(minute) + "分" + formatTime(second)+'秒';
      // }else if(hour != 0){
      //   return formatTime(hour) + ":" + formatTime(minute) + ":" + formatTime(second)+'';
      // }else if(minute !=0){
      //   return formatTime(minute) + ":" + formatTime(second)+'';
      // }else if(second!=0){
      //   return formatTime(second)+'';
      // }else {
      //   return '';
      // }

      if (day != 0) {
        return formatTime(day) +
            '天' +
            formatTime(hour) +
            "小时" +
            formatTime(minute) +
            "分" +
            formatTime(second) +
            '秒';
      } else if (hour != 0) {
        return formatTime(hour) +
            ":" +
            formatTime(minute) +
            ":" +
            formatTime(second) +
            '';
      } else if (minute != 0) {
        return formatTime(hour) +
            ":" +
            formatTime(minute) +
            ":" +
            formatTime(second) +
            '';
      } else if (second != 0) {
        return formatTime(hour) +
            ":" +
            formatTime(minute) +
            ":" +
            formatTime(second) +
            '';
      } else {
        return "";
      }
    }else{
      return "";
    }

  }

  //数字格式化，将 0~9 的时间转换为 00~09
  static String formatTime(int timeNum) {
    return timeNum < 10 ? "0" + timeNum.toString() : timeNum.toString();
  }

  _cancelTimer() {
    //界面销毁时记得取消计时器
    if (_timer != null) {
      _timer!.cancel();
    }
  }

//需要使用时调用开始倒计时
  _startTimer() {
    //设置 1 秒回调一次
    const period = const Duration(seconds: 1);
    _timer = Timer.periodic(period, (timer) {
      print(leftSeconds);
      //秒数减一，更新界面
      if(leftSeconds.toString().length > 0){
        setState(() {
          leftSeconds--;
        });
      }

      if (leftSeconds == 0) {
        //倒计时秒数为0，取消定时器
        print('我被取消了  ');
        _cancelTimer();
      }
    });
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // for (int i = 0; i < 20; i++) {
    //   dataList.add({
    //     "id": i,
    //     "url": "http://rec6p45ah.hn-bkt.clouddn.com/scy.jpg",
    //     "dataTime": "",
    //     "title": "说唱俑",
    //     "type": "3D",
    //     "orgAddress": "四川博物院",
    //     "initPrice": "25.00",
    //     "productCount": "10000",
    //     "orgLogo": "http://rec6p45ah.hn-bkt.clouddn.com/scbwy.jpg"
    //   });
    // }
    getPorducctList();
    _startTimer();
  }

  void getPorducctList() async{
    var result = await Dio().post(
        API.reqUrl+"/api/GxProduct/fint/all/1/10",
        //请求参数
        data: {

        },
        //请求头
        options: Options(
        headers: {
        "token": "sldkfjslkdgjslkd"
        }
        ));
      print(result.data["message"]);
      print(result.data["flag"]);
      print(result.data["dataObj"]);

    List<ProductList?> list = (result.data["dataObj"] as List<dynamic>)
        .map((e) => ProductList.fromMap((e as Map<String, dynamic>)))
        .toList();
    setState(() {
      mapLists = list;
    });

  }

  int productTime(String time){

    return int.parse(DateTime.parse(time).millisecondsSinceEpoch.toString());
  }


  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
    _timer!.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: Padding(
          padding: EdgeInsets.only(bottom: 40),
          child: Container(
      width: MediaQuery.of(context).size.width,
      height: MediaQuery.of(context).size.height,
      child: ListView(
          children: mapLists.map((e) => Padding(
            padding: EdgeInsets.only(
                left: 10,
                right: 10,
                bottom: 30
            ),
            child: Container(
              width: double.infinity,
              height: 500,
              decoration: BoxDecoration(
                color: Color.fromRGBO(43, 44, 45, 1),
                borderRadius: BorderRadius.circular(30),
                gradient: LinearGradient(
                    begin: Alignment.topLeft,
                    end: Alignment.bottomLeft,
                    colors: [
                      Color.fromRGBO(50, 55, 58, 1),
                      Color.fromRGBO(43, 44, 45, 1),
                    ]),
              ),
              child: Stack(
                children: [

                  GestureDetector(
                    onTap: (){
                      // print("-----------------------------");
                      // print((int.parse(DateTime.parse(e!.productTime.toString()).millisecondsSinceEpoch.toString()) - int.parse(new DateTime.now().millisecondsSinceEpoch.toString())).toString());
                      // print(productTime(e.productTime.toString()).toString());
                      // print(int.parse(new DateTime.now().millisecondsSinceEpoch.toString()).toString());
                      // print(productTime(e.productTime.toString()) - int.parse(new DateTime.now().millisecondsSinceEpoch.toString()));
                      // print("===========================");
                      if(productTime(e!.productTime.toString()) - int.parse(new DateTime.now().millisecondsSinceEpoch.toString()) < 0){
                        Navigator.of(context).pushNamed("digitaldetail",arguments: e.productCode.toString());
                        context.read<LoginProvider>().setProductDetailCode(e.productCode.toString());

                      }else{
                        BrnToast.show(
                          "还未开售..",
                          context,
                          // preIcon: Image.asset(
                          //   "assets/image/icon_toast_success.png",
                          //   width: 24,
                          //   height: 24,
                          // ),
                          duration: BrnDuration.short,
                        );
                      }


                    },
                    child: Container(
                      width: double.infinity,
                      height: 380,
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(30),
                        image: DecorationImage(
                            image: NetworkImage(e!.productImage.toString()),
                            fit: BoxFit.fill),
                      ),
                    ),
                  ),
                  //new DateTime.now().millisecondsSinceEpoch.toString()  当前时间搓
                  //Positioned(top: 80,child: Container(width: 300,height: 40,child:  Text(DateTime.parse(e.productTime.toString()).millisecondsSinceEpoch.toString(),),color: Colors.green,),),
                  //Positioned(top: 110,child: Container(width: 300,height: 40,child:  Text(new DateTime.now().millisecondsSinceEpoch.toString(),),color: Colors.green,),),
                  //Positioned(top: 110,child: Container(width: 300,height: 40,child:  Text((int.parse(DateTime.parse(e.productTime.toString()).millisecondsSinceEpoch.toString()) - int.parse(new DateTime.now().millisecondsSinceEpoch.toString())).toString()),color: Colors.green,),),
                  Positioned(
                    left: 18,
                    top: 15,
                    child: Container(
                      //width: 150,
                      height: 35,
                      decoration: BoxDecoration(
                        color: Colors.black,
                        borderRadius: BorderRadius.circular(35),
                      ),
                      child: Padding(
                        padding: EdgeInsets.only(left: 5, right: 5),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                          children:productTime(e.productTime.toString()) - int.parse(new DateTime.now().millisecondsSinceEpoch.toString()) > 0 ?  [
                            Icon(
                              Icons.timer,
                              size: 16,
                              color: Colors.lightGreenAccent,
                            ),
                             Text(
                               "发售倒计时  ",
                              style: TextStyle(
                                  color: Colors.lightGreenAccent, fontSize: 14),
                            ),
                            Text(
                              constructTime(productTime(e.productTime.toString()) - int.parse(new DateTime.now().millisecondsSinceEpoch.toString())),
                              style: TextStyle(
                                  color: Colors.lightGreenAccent, fontSize: 14),
                            )
                          ]:[
                            Icon(
                              Icons.timer,
                              size: 16,
                              color: Colors.lightGreenAccent,
                            ),
                            Text(
                              e.productStock > 0?"正在发售" :"已售馨  ",
                              style: TextStyle(
                                  color: Colors.lightGreenAccent, fontSize: 14),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ),
                  Positioned(
                      bottom: 16,
                      child: Container(
                        margin: EdgeInsets.only(left: 10, top: 20),
                        width: MediaQuery.of(context).size.width,
                        height: 90,
                        decoration: BoxDecoration(borderRadius: BorderRadius.circular(90)),
                        child: Column(
                          children: [
                            Container(
                              child: Row(
                                children: [
                                  Text(
                                    e.productTitle.toString(),
                                    style: TextStyle(
                                        fontSize: 20,
                                        color: Colors.white,
                                        fontWeight: FontWeight.w600),
                                  ),
                                  SizedBox(
                                    width: 5,
                                  ),
                                  Text(
                                    "3D",
                                    style: TextStyle(
                                        fontSize: 16, color: Colors.white),
                                  ),
                                  //Icon(Icons.delivery_dining)
                                ],
                              ),
                            ),
                            SizedBox(
                              height: 8,
                            ),
                            Container(
                              child: Row(
                                children: [
                                  Container(
                                    alignment: Alignment.center,
                                    width: 46,
                                    height: 20,
                                    color: Color.fromRGBO(243, 224, 188, 1),
                                    child: Text("限量",style: TextStyle(color: Colors.black),),
                                  ),
                                  Container(
                                    alignment: Alignment.center,
                                    width: 80,
                                    height: 20,
                                    color: Color.fromRGBO(75, 75, 76, 1),
                                    child: Text(
                                      e.productCount.toString()+"份",
                                      style: TextStyle(
                                          color:
                                          Color.fromRGBO(241, 222, 187, 1)),
                                    ),
                                  )
                                ],
                              ),
                            ),
                            SizedBox(height: 5,),
                            Expanded(
                              child: Container(
                                width: MediaQuery.of(context).size.width,
                                height: 30,
                                //color: Colors.orange,
                                child: Row(
                                  mainAxisAlignment:
                                  MainAxisAlignment.spaceBetween,
                                  children: [
                                    Row(
                                      children: [
                                        Padding(
                                          padding: EdgeInsets.all(0),
                                          child: Container(
                                            width: 20,
                                            height: 20,
                                            decoration: BoxDecoration(
                                                borderRadius:
                                                BorderRadius.circular(20),
                                                image: DecorationImage(
                                                    image: NetworkImage(
                                                        e.orgLogo),
                                                    fit: BoxFit.fill)),
                                          ),
                                        ),
                                        SizedBox(width: 10,),
                                        Container(
                                          child: Text(
                                            e.orgName,
                                            style: TextStyle(
                                                fontSize: 16,
                                                color: Colors.white),
                                          ),
                                        )
                                      ],
                                    ),
                                    Container(
                                      margin: EdgeInsets.only(right: 45),
                                      child: Text("¥"+e.initPrice.toString()+".00",style: TextStyle(color: Colors.white,fontSize: 25,fontWeight: FontWeight.w600),),
                                    )
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ))
                ],
              ),
            ),
          ),).toList(),
      ),
    ),
        ));
  }
}
